package com.chapter2json.demo.controller;

import com.alibaba.fastjson.JSON;
import com.chapter2json.demo.pojo.Pet;
import com.chapter2json.demo.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/tojson")
public class TestController {

    @RequestMapping("/jsonTest")
    public String jsonTest() {
        User user1 = new User("gameboy", "23234");
        User user2 = new User("steamboy", "23335");
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);

        // 得到对象的json数据
        String ListUserJson = JSON.toJSONString(userList);

        // 返回json串
        return ListUserJson;
    }

    /**
     * 返回json的三个步骤
     * 1. 添加starter场景启动
     * 2. 在controller添加RestController注解
     * 3. 直接在请求的方法上返回对象即可
     * springboot会自动把返回的对象解析成json字符串返回
     * @return
     */
    @RequestMapping("/jsonTest2")
    public List<User> jsonTest2() {
        User user1 = new User("gameboy", "23234");
        User user2 = new User("steamboy", "23335");
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);

        // 直接返回java对象
        return userList;
    }

    /**
     * 之前的案例返回的都是一个字符串
     * 现在想要返回json字符串，在springboot项目中直接返回对象即可。
     *
     * @return
     */
    @RequestMapping("/pet")
    public Pet getPet() {
        return new Pet((long) 1, "团团", 2, "brown", " a cute puppy");
    }

    @RequestMapping("/petList")
    public List<Pet> getPetList() {
        List<Pet> petList = new ArrayList<>();
        Pet pet1 = new Pet((long) 2, "JackM", 1, "silver", " a cute cat of Silver gradient");
        Pet pet2 = new Pet((long) 3, "FatFat", 1, "silver", " a chubby cat");

        petList.add(pet1);
        petList.add(pet2);

        return petList;
    }
}